<template>
    <div v-dialog-drag>
      <el-dialog
        :title="id === 0 ? '新增' : '编辑'"
        :visible.sync="dialogVisible"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="true"
        :show-close="false"
        @close="close"
      >
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
          <el-form-item label="模板名称" prop="name" label-width="100px">
            <el-input v-model="ruleForm.name" size="mini" clearable placeholder="请输入报警名称" />
          </el-form-item>
          <el-form-item label="报警类型" prop="name" label-width="100px">
            <el-radio-group v-model="ruleForm.type" @change="typeChange">
              <el-radio :label="2">设备上报</el-radio>
              <el-radio :label="1">数据匹配</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="参数模板" prop="param_tem_id"  label-width="100px">
            <el-select
              v-model="ruleForm.param_tem_id"
              @change="changeParamTem"
              size="mini"
              placeholder="请选择"
              style="width: 100%">
              <el-option
                v-for="item in temList"
                :key="item.id"
                :label="item.temp_name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参数" label-width="100px">
            <div v-if="!ruleForm.param_tem_id" style="color: #CCCCCC">请选择参数模板</div>
            <el-checkbox-group
              v-if="ruleForm.param_tem_id"
              v-model="temIds"
              size="mini">
              <template v-for="(item, index) in temDetail">
                <el-checkbox  @change="checkChange1($event, item)" :label="item.id" :value="item.id" size="mini">{{ item.data_name }}</el-checkbox>
              </template>
            </el-checkbox-group>
          </el-form-item>
          <!-- 数据匹配 -->
          <el-form-item label="配置参数" label-width="100px" v-if="ruleForm.type === 1">
            <el-table
              :data="ruleForm.tem_child"
              border
              size="mini"
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                label="级别"
                align="center"
                width="150">
              </el-table-column>
              <el-table-column
                prop="label_name"
                align="center"
                label="名称">
              </el-table-column>
              <el-table-column
                prop="start"
                align="center"
                label="最小值">
                <template slot-scope="scope">
                  <el-input-number size="mini" style="width: 100%" v-model="scope.row.start"  label="描述文字"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="end"
                align="center"
                label="最大值">
                <template slot-scope="scope">
                  <el-input-number size="mini" style="width: 100%" v-model="scope.row.end"  label="描述文字"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <!-- 设备上报 -->
          <el-form-item label="配置参数" label-width="100px" v-if="ruleForm.type === 2">
            <el-table
              :data="ruleForm.tem_child"
              border
              size="mini"
              style="width: 100%"
            >
              <el-table-column
                prop="label_name"
                align="center"
                label="名称">
              </el-table-column>
              <el-table-column
                prop="start"
                align="center"
                label="报警级别">
                <template slot-scope="scope">
                  <el-select
                    size="mini"
                    v-model="scope.row.level_id"
                    @change="levelIdChange($event, scope.$index)"
                    placeholder="请选择">
                    <el-option
                      v-for="item in levelList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                prop="end"
                align="center"
                label="阈值">
                <template slot-scope="scope">
                  <el-input-number size="mini" style="width: 100%" v-model="scope.row.start"  label="描述文字"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                prop="end"
                align="center"
                label="操作">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.add_flag === 1" size="mini" type="success" icon="el-icon-plus" @click="addOrReduce(1, scope.$index)">新增</el-button>
                  <el-button v-if="scope.row.add_flag === 0" size="mini" type="danger" icon="el-icon-minus" @click="addOrReduce(2, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            size="mini"
            @click="close"
          >取消</el-button>
          <el-button
            type="primary"
            size="mini"
            @click="save"
          >确认</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
  import { updateWarningTem, createWarningTem, detailWarningTem, allTemList, warningAllList } from '@/api/warning'
  import { detailTemplate } from '@/api/template'
  import defaultOptions from "../../../../components/MarkdownEditor/default-options";
  export default {
    name: "detail",
    props: {
      id: {
        type: Number,
        default: 0
      },
    },
    data() {
      return {
        temIds: [], // 选中的参数id
        temList: [], // 所有模板参数数据
        levelList: [], // 所有等级数据
        dialogVisible: false,
        temDetail: [], // 模板详情
        ruleForm: {
          name: '',
          param_tem_id: null, // 参数模板id
          type: 2, // 报警类型: 1数据匹配， 2设备上报异常
          tem_child: [] // 模板配置项
        },
        rules: {
          name: [
            {required: true, message: '请输入报警模板名称', trigger: 'blur'}
          ],
          param_tem_id: [
            {required: true, message: '请选择参数模板', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择报警类型', trigger: 'blur'}
          ]
        }
      }
    },
    created() {
      // 获取所有参数模板
      this.getAllTem()
      // 获取所有级别
      this.getAllLevel()
    },
    watch: {
      id(newV, oldV){
        if (newV === 0) {
          this.resetForm()
        } else {
          this.getDetail()
        }
      }
    },
    methods: {
      /*
      * @description: 报警级别改变
      * @param: 1: 新增， 2：删除
      * @author: 书童
      * */
      addOrReduce(type, index) {
        if (type === 1) {
          let obj = {
            param_id: this.ruleForm.tem_child[index].param_id,
            column_name: this.ruleForm.tem_child[index].column_name,
            label_name: this.ruleForm.tem_child[index].label_name,
            start: null,
            end: null,
            level_id: null,
            name: null,
            describe: null,
            add_flag: 0
          }
          this.ruleForm.tem_child.splice(index + 1, 0, obj)
        } else if (type === 2) {
          this.ruleForm.tem_child.splice(index, 1)
        }
      },
      /*
      * @description: 报警级别改变
      * @author: 书童
      * */
      levelIdChange(e, index) {
        for (let i = 0; i < this.levelList.length; i++) {
          if (this.levelList[i].id === e) {
            this.ruleForm.tem_child[index].level_id = this.levelList[i].id
            this.ruleForm.tem_child[index].name = this.levelList[i].name
            this.ruleForm.tem_child[index].describe = this.levelList[i].describe
            break
          }
        }
        // this.ruleForm.tem_child[index].level_id = e.id
        // this.ruleForm.tem_child[index].name = e.name
        // this.ruleForm.tem_child[index].describe = e.describe
      },
      /*
      * @description: 选中的报警类型改变
      * @author: 书童
      *  报警类型改变之后清空参数和配置参数
      * */
      typeChange(e) {
        console.log('typechange', e)
        this.ruleForm.tem_child = []
        this.ruleForm.param_tem_id = null
        this.ruleForm.temIds = []
      },
      /*
      * @description: 选中的参数改变
      * @author: 书童
      * */
      checkChange1(e, item) {
        // 选中的数据
        let flag = false
        flag = this.ruleForm.tem_child.some((n) => {
          return n.label_name == item.data_name
        })
        if (e) {
          // 避免重复添加
          if (!flag && this.ruleForm.type === 1) {
            this.levelList.forEach(v => {
              let obj = {
                param_id: item.id,
                column_name: item.column_name,
                label_name: item.data_name,
                start: null,
                end: null,
                level_id: v.id,
                name: v.name,
                describe: v.describe
              }
              this.ruleForm.tem_child.push(obj)
            })
          } else if(!flag && this.ruleForm.type === 2) {
            // 不填入报警等级数据，让用户把自己选择
            let obj = {
              param_id: item.id,
              column_name: item.column_name,
              label_name: item.data_name,
              start: null,
              end: null,
              level_id: null,
              name: null,
              describe: null,
              add_flag: 1
            }
            this.ruleForm.tem_child.push(obj)
          }
        } else {
        //  取消选中的数据
          if (flag && this.ruleForm.tem_child.length > 1) {
            for (let i = this.ruleForm.tem_child.length - 1; i >= 0; i-- ) {
              if (this.ruleForm.tem_child[i].column_name === item.column_name) {
                this.ruleForm.tem_child.splice(i, 1)
              }
            }
          } else if (flag && this.ruleForm.tem_child.length === 1) {
            console.log(2222)
            this.ruleForm.tem_child = []
          }
        }
      },
      /**
       * @description: 获取所有级别
       * @author: 书童
       */
      getAllLevel() {
        warningAllList().then(res => {
          this.levelList = res.data.list
        })
      },
      /**
       * @description: 获取详情数据
       * @author: 书童
       */
      getDetail() {
        detailWarningTem({id: this.id}).then(res => {
          this.ruleForm = {...res.data}
          detailTemplate({id: res.data.param_tem_id}).then(res1 => {
            this.temDetail = res1.data.dataList.templates
          }).then(() => {
            this.ruleForm.tem_child.forEach(item => {
              this.temIds.push(item.param_id)
            })
            let arr = [...new Set(this.temIds)]
            // this.temIds = [...arr]
            this.$set(this, 'temIds', arr)
            console.log('选中', this.temIds)
          })
        })
      },
      /**
       * @description: 切换选中的模板 ，获取模板详情
       * @author: 书童
       */
      changeParamTem(e) {
        detailTemplate({id: e}).then(res => {
          this.temDetail = res.data.dataList.templates
          this.ruleForm.tem_child = []
        })
      },
      /**
       * @description: 新增/编辑
       * @author: 书童
       */
      save() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            // 先判断是新增还是编辑
            let promise = new Promise((resolve,reject) => {
              if (this.id === 0) {
                createWarningTem(this.ruleForm).then(res => {
                  console.log(res)
                  resolve()
                })
              } else {
                // 去除id字段
                let newObj = {}, newArr = []
                this.ruleForm.tem_child.forEach((item, index, arr) => {
                  for ( var key in item) {
                    if(key != 'id'){
                      newObj[key] = item[key];
                    }
                  }
                  newArr.push(newObj);
                  newObj = {};
                })
                this.ruleForm.tem_child = newArr
                updateWarningTem(this.ruleForm).then(res => {
                  resolve()
                })
              }
            })
            promise.then(() => {

              // 刷新表格数据,关闭表格
              this.$emit('reload')
              this.close()
            }).then(() => {
              console.log(111111)
              this.$message({
                type: 'success',
                message: this.id === 0 ? '新增成功' : '编辑成功'
              })
            })
          }
        })
      },
      open() {
        this.dialogVisible = true
      },
      close() {
        this.resetForm()
        this.$emit('resetId')
        this.dialogVisible = false
      },
      resetForm() {
        this.ruleForm = {
          name: '',
          param_tem_id: null, // 参数模板id
          type: 2, // 报警类型: 1自己匹配， 2设备上报异常
          tem_child: [] // 模板配置项
        }
        this.temIds = []
      },
      /**
       * @description: 获取所有参数模板
       * @author: 书童
       */
      getAllTem() {
        allTemList().then(res => {
          this.temList = res.data.data
        })
      }
    }
  }
</script>

<style scoped>

</style>
